from datetime import datetime
import logging
import os
import time

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from playwright.async_api import async_playwright

from forward.api.schema.card import ActivateInfoSchema, ContactSchema, CreateCellSchema, PlayerSchema, PlayerSchemaV1, ProductInfoSchema, VisitorSchema
from forward.spider.yts_card_async import CardActivatorAsync
from forward.spider.yts_card_api import YTSCardApi
from forward.utils.encryption import encrypt_long

# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class CardService:
    @classmethod
    def instance(cls):
        if not hasattr(cls, '_instance'):
            cls._instance = cls()
        return cls._instance

    async def activate_card(self, visitor: PlayerSchemaV1):
        card_activator = CardActivatorAsync()
        try:
            await card_activator.start()
            await card_activator.activate_card(
                name=visitor.name,
                mobile=visitor.mobile,
                id_number=visitor.id_number,
                code=visitor.code
            )
            response_data = card_activator.get_response_data()
            logger.info("Card activation successful: %s", response_data)
            return response_data
        except RuntimeError as e:
            logger.error("RuntimeError during card activation: %s", e)
        except Exception as e:
            logger.error("Error during card activation: %s", e)
        finally:
            await card_activator.close()

    async def activate_card_api(self, player_in: PlayerSchema):
        # 实例化
        yts_card_api = YTSCardApi()
        # 获取产品信息
        product_info_res, token_ = yts_card_api.get_product_info(
            product_price_id=player_in.card_info.product_price_id,
            partner_code=player_in.card_info.partner_code,
        )
        if not product_info_res:
            raise Exception("获取产品信息失败")

        # print("product_info: %s", product_info_res.get("data"))
        # print("token", token_)
        # return
        product_info = ProductInfoSchema(**product_info_res.get("data"))
        if not product_info:
            raise Exception("获取产品信息失败")
        if not token_:
            raise Exception("获取产品信息失败")
        # 构造数据
        activate_info = await self.construction_activate_info(player_in, product_info, token_)

        # 加密
        encryption_acitivate_info = encrypt_long(activate_info.model_dump_json())
        logger.info("encryption_acitivate_info: %s", encryption_acitivate_info)
        # return
        res = yts_card_api.activate_card(
            encryption_acitivate_info, activate_info.token)
        # print(res.content)
        return JSONResponse(content=jsonable_encoder(
            {
                "code": 200,
                "msg": "",
                "data": res
            },
            by_alias=False,
        )
        )

    async def encrypt(self, actvate_in: ActivateInfoSchema):
        # 启动 Playwright
        play = await async_playwright().start()
        browser = await play.chromium.launch(headless=False, slow_mo=1000)
        page = await browser.new_page()

        # 假设 js 文件路径是相对于当前文件的路径
        js_file_path = os.path.join(os.path.dirname(
            __file__), '..', '..', '..', 'forward', 'js', 'encrypt.js')

        # 读取 JavaScript 文件内容
        with open(js_file_path, 'r', encoding='utf-8') as file:
            js_code = file.read()

        # 执行 JavaScript 代码
        result = await page.evaluate(js_code, actvate_in.model_dump_json)
        logger.info("JavaScript execution result: %s", result)

        # 关闭浏览器
        await browser.close()
        await play.stop()

        # 返回加密后的信息
        return result

    async def construction_activate_info(self, player_in: PlayerSchema, product_info: ProductInfoSchema, token_: str):
        '''
        {
        "balance": "",
        "contact": {
                "credential": "410105196503018415", 身份证
                "credentialType": "1", 固定
                "faceImageId": "",
                "name": "李修岭", 姓名
                "phone": "15136107396", 电话
                "visitorPoint": ""
        },
        "createCells": [
                {
                        "bookQuantity": 1,
                        "productPriceId": "1781",
                        "salePrice": 91,
                        "settleMoney": 91,
                        "startDate": "2025-01-17",
                        "timeCode": "",
                        "visitors": [
                                {
                                        "countryAlphaCode": "",
                                        "countryName": "",
                                        "credential": "410105196503018415", 身份证
                                        "credentialType": "1", 固定
                                        "faceImageId": "",
                                        "idCardType": "idcard",
                                        "idIndex": "01737051364335", 列表id+时间戳
                                        "index": 0,
                                        "name": "李修岭"
                                }
                        ]
                }
        ],
        "ecologyMemberId": "",
        "giftCouponQrCodeId": 66883, card_info.giftCouponQrCodeId
        "memberTag": "",
        "partnerMerchantId": 2289, card_info.partnerMerchantId
        "paymentMode": 1,
        "performScreeningId": "",
        "priceGroupType": 3,
        "productCategory": 502,
        "scheduleCode": ""
        }
        '''
        '''
        {
            "success": true,
            "code": null,
            "desc": null,
            "previousUrl": null,
            "currentUrl": null,
            "nextUrl": null,
            "data": {
                "giftCouponQrCodeId": 13251,
                "merchantId": 2,
                "partnerMerchantId": 2289,
                "partnerCode": "ezMPLGBZgDfvAodjhzJVsQ",
                "giftCouponOrderId": 5,
                "encryptId": "645f86b5cec4da0a56ffea7a891720c9",
                "cardNo": "00001201",
                "allotQuantity": 1,
                "activateQuantity": 0,
                "couponBatchId": 19,
                "couponName": "25年199元实体卡",
                "expiredTime": "2025-03-31 23:55:54",
                "description": "199年卡权益：\r\n权益：免云台山景区全年门票、观光车票、凤凰岭索道、茱萸峰索道、360球幕影院。\r\n（除以上权益外，不包含各景区其他二次消费项目）\r\n实体年卡需在2025年3月31日前输入身份证号激活，过期作废。\r\n购票须知：\r\n1、云台山年卡实名制预定，使用时间自激活之日（最晚需在2025年3月31日前激活）至2025年12月31日（五一、十一假期除外），刷身份证可无限次游览云台山景区（199元年卡包含全年景区门票、观光车票、凤凰岭双程索道票，茱萸峰双程索道、云台山360球幕影院）；\r\n2、免门票、免车票政策：仅限6周岁以下及身高1.4米以下人群；免索道票政策；身高1.2米以下儿童；\r\n3、云台山年卡购买后不退不改，使用时刷本人身份证即可无限次游览景区；\r\n4、购票后，关注“云台山景区”微信公众号菜单栏点击“票号查询”即可获取本人年卡信息；\r\n5、咨询电话：0391-7709300。（备注：出行前请关注景区微博、微信公众号，如遇天气等不可抗力因素影响游览，请及时调整行程）\r\n以上内容最终解释权归云台山景区所有",
                "backgroundPictureUrl": "",
                "productSpuId": 118,
                "productCategoryId": 502,
                "productSkuId": 599,
                "productPriceId": 1784,
                "productPriceListId": 0,
                "qrCodeStatus": -1,
                "webOrderNo": ""
            },
            "page": null,
            "params": null
        }

        {
        "merchantId": 2,
        "productPriceId": 1781,
        "parentProductPriceId": 0,
        "paymentModeList": [
            1
        ],
        "productCategoryId": 502,
        "productSceneTypeId": 0,
        "productSpuId": 117,
        "productSpuName": "25年云台山年卡（99元）",
        "poiId": 4,
        "poiName": "云台山年卡",
        "poiLinkMobile": null,
        "productSkuId": 598,
        "productSkuName": "25年云台山年卡原价99元(实体卡)",
        "studentTicketTag": 0,
        "marketPriceId": null,
        "spuPictureList": [],
        "skuPictureList": [],
        "spuDescription": "",
        "skuDescription": "",
        "bookingRemind": "可随时预订",
        "marketPrice": 91.0,
        "settlePrice": 91.0,
        "memberPrice": null,
        "groupBuyPrice": null,
        "marketSharePrice": null,
        "marketPromotePrice": null,
        "marketManagePrice": null,
        "lowestPrice": 91.0,
        "stockPlanType": null,
        "stock": null,
        "soldQuantity": null,
        "bookPlanId": 50,
        "minimumQuantity": 1,
        "maximumQuantity": 9999,
        "startDate": "2025-01-25",
        "endDate": "2025-03-31",
        "linkMobile": true,
        "linkName": true,
        "linkCredential": true,
        "linkCredentialTypes": "1,6",
        "realNameBookRuleTypes": null,
        "realNameType": true,
        "visitorName": true,
        "visitorCredential": true,
        "visitorCredentialTypes": "1,6,5",
        "collectFaceTag": false,
        "collectFaceType": null,
        "cardCaptureTag": false,
        "cardImageQuantity": 0,
        "officeLetterTag": false,
        "officeLetterUrls": null,
        "priceDateDetailList": [
            {
                "priceDatePlanId": 69,
                "beginDate": "2024-12-19",
                "endDate": "2025-03-31",
                "validWeekdays": "1,2,3,4,5,6,0"
            }
        ],
        "webUploadConfig": null,
        "refundType": 0,
        "allowRefundTag": false,
        "refundBeforeUse": false,
        "allowPartRefund": false,
        "allowModify": false,
        "advanceDay": null,
        "advanceTime": null,
        "ticketActiveType": 1,
        "useDatePlanId": 29,
        "validDateName": "有效期：2024-12-19 ~ 2025-12-31",
        "useDatePlanType": 2,
        "relativeUnit": 1,
        "relativeQuantity": 0,
        "lineDays": null,
        "startCantonName": null,
        "productOverview": null,
        "lineSchedule": null,
        "bookDescription": null,
        "lineScheduleJsons": null,
        "couponValidType": null,
        "couponStartDate": null,
        "couponEndDate": null,
        "couponValidHour": null,
        "couponScopeType": null,
        "siteChannelTypes": null,
        "description": null,
        "insuranceTag": false,
        "electronicFenceTag": false,
        "memberPriceTag": null,
        "hasExistPerformTag": false,
        "productHotelConfig": null,
        "performProductConfig": null,
        "productLongCardConfig": null,
        "rentProductInfoConfig": null,
        "productSkuExtraConfig": null,
        "specificationAttribute": null,
        "validTag": null
    }
        '''
        activate_info = ActivateInfoSchema(
            balance='',
            contact=ContactSchema(
                credential=player_in.id_number,
                credential_type="1",
                face_image_id='',
                name=player_in.name,
                phone=player_in.mobile,
                visitor_point=""
            ),
            create_cells=[
                CreateCellSchema(
                    book_quantity=1,
                    product_price_id=player_in.card_info.product_price_id,
                    sale_price=product_info.market_price,
                    settle_money=product_info.settle_price,
                    start_date=datetime.now().strftime("%Y-%m-%d"),
                    time_code='',
                    visitors=[
                        VisitorSchema(
                            country_alpha_code='',
                            country_name='',
                            credential=player_in.id_number,
                            credential_type="1",
                            face_image_id='',
                            id_card_type="idcard",
                            id_index=f"0{int(time.time())}",
                            index=0,
                            name=player_in.name,
                        )
                    ]
                )
            ],
            ecology_member_id='',
            gift_coupon_qr_code_id=player_in.card_info.gift_coupon_qr_code_id,
            member_tag="",
            partner_merchant_id=player_in.card_info.partner_merchant_id,
            payment_mode=1,
            perform_screening_id='',
            price_group_type=3,
            product_category=product_info.product_category_id,
            schedule_code='',
            token=token_
        )
        '''
        "ecologyMemberId": "",
        "giftCouponQrCodeId": 66883, card_info.giftCouponQrCodeId
        "memberTag": "",
        "partnerMerchantId": 2289, card_info.partnerMerchantId
        "paymentMode": 1,
        "performScreeningId": "",
        "priceGroupType": 3,
        "productCategory": 502,
        "scheduleCode": ""
        '''
        return activate_info
